package com.sen.app.timemail;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.sen.app.timemail.entity.RecipientInfoEntity;
import com.sen.app.timemail.services.impl.SendEmailServiceImpl;
import com.sen.app.timemail.utils.DirUtils;

/**
 * 程序主函数，启动点
 * 
 * @author sen
 */
public class Main {
	
	private static Logger logger = Logger.getLogger(Main.class);
	
	/**
	 * 命令参数
	 */
	private static final String SEND = "send";
	private static final String CREATEXLS = "createXls";
	
    public static void main(String[] args) {
    	String log4jPath = DirUtils.getConfDir() + File.separator  + "log4j.properties";
    	PropertyConfigurator.configure(log4jPath);
    	
		String arg =  SEND;
		if (ArrayUtils.isNotEmpty(args) && StringUtils.isNotBlank(args[0])) {
			arg = args[0];
		}
		
		if (SEND.equalsIgnoreCase(arg)) {
			send();
		} else if (CREATEXLS.equalsIgnoreCase(arg)) {
			createXls();
		}
	}
	
	/**
	 * 发送邮件命令
	 */
    @SuppressWarnings("unused")
	public static void send() {
    	logger.info("程序启动...");
    	String home = DirUtils.getUserDir();
    	logger.debug("home: " + home);
    	
    	String applicationContextXmlPath = DirUtils.getConfDir() + File.separator + "applicationContext.xml";
    	File xml = new File(applicationContextXmlPath);
    	if (null != xml && !xml.exists()) {
    		logger.warn("未找到applicationContext.xml配置文件。程序退出！");
    		return;
    	}
    	
    	String[] configXmls = new String[] { xml.getAbsolutePath() };
		ApplicationContext applicationContext = new FileSystemXmlApplicationContext(configXmls);
    	
		logger.info("启动成功!");
	}
	
    /**
     * 创建xls文件
     */
	public static void createXls() {
		logger.info("正在生成xls文件...");
		List<RecipientInfoEntity> datas = new SendEmailServiceImpl().getSendFailRecipientEmail();
        if (CollectionUtils.isEmpty(datas)) {
        	logger.info("未生成xls文件,原因:没有数据可处理.");
			return;
		}
        
        // 创建目录
        File tempDir = new File(DirUtils.getTempDir());
        if (tempDir == null || !tempDir.exists()) {
		    tempDir.mkdirs();
		}
        
        File outputFile = new File(DirUtils.getTempDir() + File.separator + "emailTable.xls");
		FileOutputStream out = null;
		try {
			HSSFWorkbook wb = new HSSFWorkbook();
	        HSSFSheet sheet = wb.createSheet();
	        HSSFRow titleRow = sheet.createRow(0);
	        HSSFCell firstNameTitleCell = titleRow.createCell(0);
	        firstNameTitleCell.setCellValue("First Name");
	        HSSFCell lastNameTitleCell = titleRow.createCell(1);
	        lastNameTitleCell.setCellValue("Last Name");
	        HSSFCell emailTitleCell = titleRow.createCell(2);
	        emailTitleCell.setCellValue("Email");
	        
	        for (int i = 0; i < datas.size(); i++) {
	        	RecipientInfoEntity entity = datas.get(i);
	        	HSSFRow row = sheet.createRow(i + 1);
	        	HSSFCell firstNameCell = row.createCell(0);
		        firstNameCell.setCellValue(entity.getFirstName());
		        HSSFCell lastNameCell = row.createCell(1);
		        lastNameCell.setCellValue(entity.getLastName());
		        HSSFCell emailCell = row.createCell(2);
		        emailCell.setCellValue(entity.getEmailAddr());
	        }
	        out = new FileOutputStream(outputFile);
			wb.write(out);
	        out.close();
	        logger.info("生成xls文件成功,位置:".concat(outputFile.getAbsolutePath()));
		} catch (IOException e) {
			logger.info("获取文件".concat(outputFile.getAbsolutePath())
					.concat("的输入流出错!原因:").concat(e.getMessage()));
			logger.info("生成xls文件失败,请确认文件是否以打开.");
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
				}
			}
		}
        
	}
}
